<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <h1 style="text-align: center;">文档修改页面</h1>
            </div>
            <el-form ref="documentRef" :model="form" :rules="rules" label-position="top" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="所属档案" prop="archiveId">
                            <el-input v-model="form.archiveId" placeholder="请输入所属档案" />
                        </el-form-item>
                        <el-form-item label="文件名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入文件名称" />
                        </el-form-item>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="文件类型" prop="fileType">
                                    <el-select v-model="form.fileType" placeholder="请选择文件类型">
                                        <el-option v-for="dict in iams_media_type" :key="dict.value" :label="dict.label"
                                            :value="dict.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="文件大小(Kb)" prop="fileSize">
                                    <el-input v-model="form.fileSize" placeholder="请输入文件大小(Kb)" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="文件路径" prop="filePath">
                            <el-input v-model="form.filePath" placeholder="请输入文件路径" />
                        </el-form-item>
                        <el-form-item label="挂载目录" prop="directory">
                            <el-tree-select v-model="form.directory" :data="directory" check-strictly
                                :render-after-expand="false" style="width: 240px" @change="changeDirectory" />
                        </el-form-item>
                        <el-form-item label="存放位置" prop="fileLocation">
                            <el-input v-model="form.fileLocation" placeholder="请输入存放位置" />
                        </el-form-item>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="真实性" prop="authenticity" label-position="left">
                                    <el-switch v-model="formBoolean.authenticity" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="完整性" prop="integrity">
                                    <el-switch v-model="formBoolean.integrity" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="可用性" prop="availability">
                                    <el-switch v-model="formBoolean.availability" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="安全性" prop="security">
                                    <el-switch v-model="formBoolean.security" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="文件内容">
                            <editor v-model="form.content" :min-height="250" />
                        </el-form-item>

                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </template>
        </el-card>
    </div>
</template>

<script setup lang="js">
import { ref, computed, reactive, toRefs } from "vue";
import { useRoute } from "vue-router";
import { getDocument, updateDocument } from "@/api/manage/document";
import { getArchive, deleteDirectoryFiles, addDirectoryFiles } from "@/api/manage/archive";

const { proxy } = getCurrentInstance();
const { iams_media_type } = proxy.useDict('iams_media_type');

const route = useRoute();

const data = reactive({
    form: {},
    rules: {
        name: [
            { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
    }
});

const archive = ref({});
const directory = ref([]);
const oldDirectory = ref();
const oldData = ref({});

const { form, rules } = toRefs(data);

// 定义需要转换的字段列表
const booleanFields = ['authenticity', 'integrity', 'availability', 'security'];

// 创建中间计算属性对象
const formBoolean = reactive({});
booleanFields.forEach(field => {
    formBoolean[field] = computed({
        get: () => form.value[field] === 1,
        set: (val) => { form.value[field] = val ? 1 : 0; }
    });
});

// 取消按钮
function cancel() {
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        archiveId: null,
        xuhao: null,
        name: null,
        fileType: null,
        fileSize: null,
        filePath: null,
        fileLocation: null,
        content: null,
        authenticity: null,
        integrity: null,
        availability: null,
        security: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        directory: null
    };
    proxy.resetForm("documentRef");
}

function changeDirectory(value) {
    console.log('Directory changed to:', value);
    form.value.directory = value;
}
/** 提交按钮 */
function submitForm() {
    proxy.$refs["documentRef"].validate(valid => {
        if (valid) {
            if (form.value.directory != oldDirectory.value) {
                oldData.value = {
                    ...form.value,
                    directory: oldDirectory.value // 单独覆盖 directory
                };
                oldData.value.directory = oldDirectory.value;
                deleteDirectoryFiles(oldData.value).then(res => {
                    addDirectoryFiles(form.value).then(response => {                 //已修改
                        console.log('Directory updated successfully:', form.value);
                    }).catch(error => {
                        console.error('Error updating directory:', error);
                    });
                });
            }
            updateDocument(form.value).then(response => {
                proxy.$modal.msgSuccess("修改成功");
                proxy.$router.push({ path: "/manage/document/doc-list" });
            });
        }
    });
}

onMounted(() => {
    reset();
    const _id = route.query.id;

    getDocument(_id).then(response => {
        form.value = response.data;

        console.log('form.value.authenticity:', form.value.authenticity); // 应为 0/1
        console.log('formBoolean.authenticity:', formBoolean.authenticity.value); // 应为 true/false

        oldDirectory.value = form.value.directory;
        getArchive(response.data.archiveId).then(response => {
            // console.log('API Response:', response.data); // 添加日志输出
            if (response.code == 200 && response.data) {
                // 确保 response.data.directory 是一个数组
                let directoryData = [];
                if (typeof response.data.directory === 'string') {
                    try {
                        directoryData = JSON.parse(response.data.directory);
                    } catch (e) {
                        console.error('Failed to parse JSON:', e);
                        proxy.$modal.msgError("解析目录数据失败");
                        return;
                    }
                } else if (Array.isArray(response.data.directory)) {
                    directoryData = response.data.directory;
                }

                // console.log('directoryData:', directoryData); // 添加日志输出

                directory.value = directoryData.map(item => ({
                    value: item.id,
                    label: item.label,
                    children: item.children ? item.children.map(child => ({
                        value: child.id,
                        label: child.label
                    })) : []
                }));

                // console.log('directory.value:', directory.value); // 添加日志输出

                archive.value = response.data;
            }
        })
    });
});
</script>